#include "uploader.h"
#include <QFileInfo>
#include <QHttpPart>
#include <QNetworkReply>

Uploader::Uploader(QObject *parent)
    : QObject{parent}
{

}

void Uploader::setUp(const QString &userName)
{
    m_userName = userName;
}

bool Uploader::upload(const QString &filePath, const QString &url, const QString &fileName, const QString &formName)
{
    if(!QFile::exists(filePath))
    {
        qWarning() << "待上传文件不存在:" << filePath;
        return false;
    }
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");

    // post数据块
    QFileInfo info(filePath);
    QHttpPart part;
    QString disp = QString("form-data; user=\"%1\"; filename=\"%2\"").arg(m_userName, fileName);
    QString suffix = info.suffix();
    QString contentType;
    if("txt" == suffix || "log" == suffix)
    {
        contentType = "text/plain";
    }
    if(contentType.isEmpty())
    {
        qWarning() << "不支持的文件类型:" << filePath << suffix;
        Q_ASSERT(false);
        return false;
    }

    //组织content-dispositon
    part.setHeader(QNetworkRequest::ContentDispositionHeader, disp);
    QFile *file = new QFile(filePath);
    file->open(QFile::ReadOnly);
    //组织真正文件内容
    part.setBodyDevice(file);
    // 传输的数据块的格式
    part.setHeader(QNetworkRequest::ContentTypeHeader, contentType);

    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this);
    //加上分界线，打包
    multiPart->append(part);
    //post方式发送出去
    QNetworkReply* reply = m_mgr.post(request, multiPart);
    connect(reply, &QNetworkReply::readyRead, this, [=](){
        //  接收数据
        reply->readAll();

        // 释放内存
        // delete multiPart;
        multiPart->deleteLater();
        file->close();
        file->deleteLater();
        reply->deleteLater();
    });
    return true;
}
